/*
 * @lc app=leetcode.cn id=146 lang=typescript
 *
 * [146] LRU 缓存机制
 */

// @lc code=start

class HashListNode {
  key: number;
  value: number;
  next: HashListNode;
  prev: HashListNode;
  constructor(
    key: number = 0,
    value: number = 0,
    next: HashListNode = null,
    prev: HashListNode = null
  ) {
    this.key = key;
    this.value = value;
    this.next = next;
    this.prev = prev;
  }
  insertBefore(node: HashListNode) {
    node.next = this;
    node.prev = this.prev;
    this.prev.next = node;
    this.prev = node;
  }
  remove(): HashListNode {
    this.prev.next = this.next;
    this.next.prev = this.prev;
    this.prev = this.next = null;
    return this;
  }
}

class HashList {
  head: HashListNode;
  tail: HashListNode;
  hash: Map<number, HashListNode>;
  capcity: number;
  constructor(capcity: number) {
    this.head = new HashListNode();
    this.tail = new HashListNode();
    this.head.next = this.tail;
    this.tail.prev = this.head;
    this.hash = new Map();
    this.capcity = capcity;
  }
  put(key: number, value: number): void {
    if (this.hash.has(key)) {
      this.hash.get(key).value = value;
      this.hash.get(key).remove();
    } else {
      this.hash.set(key, new HashListNode(key, value));
    }
    this.tail.insertBefore(this.hash.get(key));
    if (this.hash.size > this.capcity) {
      this.hash.delete(this.head.next.key);
      this.head.next.remove();
    }
  }

  get(key: number): number {
    if (this.hash.has(key)) {
      const node = this.hash.get(key);
      this.tail.insertBefore(node.remove());
      return node.value;
    } else {
      return -1;
    }
  }
}

class LRUCache {
  hashlist: HashList;
  constructor(capacity: number) {
    this.hashlist = new HashList(capacity);
  }

  get(key: number): number {
    return this.hashlist.get(key);
  }

  put(key: number, value: number): void {
    this.hashlist.put(key, value);
  }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * var obj = new LRUCache(capacity)
 * var param_1 = obj.get(key)
 * obj.put(key,value)
 */
// @lc code=end
